package service

import (
	"teacher-helper/dao"
	"teacher-helper/models"
	"teacher-helper/models/request"
)

func AddOneCourse(Course models.SysCourse) error {
	return dao.DB.Create(&Course).Error
}

func GetCourseList(queryInfo request.QueryInfo) (Courses []models.SysCourse, total int, err error) {
	if queryInfo == (request.QueryInfo{}){
		err = dao.DB.Where(&models.SysCourse{CourseType:"考试课"}).Preload("Semester").Preload("Department").Find(&Courses).Count(&total).Error
		return
	}
	if queryInfo.Query == "" {
		if err = dao.DB.Model(&models.SysCourse{}).Count(&total).Error; err != nil {
			return
		}
		err = dao.DB.Limit(queryInfo.PageSize).Offset((queryInfo.PageNum - 1) * queryInfo.PageSize).Preload("Department").Preload("Semester").Find(&Courses).Error
	} else {
		if err = dao.DB.Model(&models.SysCourse{}).Where("course_name like ?", queryInfo.Query+"%").Count(&total).Error; err != nil {
			return
		}
		err = dao.DB.Where("course_name like ?", queryInfo.Query+"%").Limit(queryInfo.PageSize).Offset((queryInfo.PageNum - 1) * queryInfo.PageSize).Preload("Semester").Preload("Department").Find(&Courses).Error
	}
	return
}

func UpdateCourse(Course models.SysCourse) error {
	Course.Semester = models.SysSemester{}
	Course.Department = models.SysDepartment{}
	return dao.DB.Save(&Course).Error
}

func DeleteCourse(id int) error {
	return dao.DB.Delete(&models.SysCourse{ID:id}).Error
}
